package cn.linlane.controller.sys;

import cn.linlane.controller.BaseController;
import cn.linlane.entity.errors.MyError;
import cn.linlane.entity.exception.MyException;
import cn.linlane.entity.sys.SysRole;
import cn.linlane.entity.sys.SysUser;
import cn.linlane.service.sys.ShiroService;
import cn.linlane.service.sys.SysRoleService;
import cn.linlane.service.sys.SysUserService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.util.Assert;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import java.util.Set;


@Api(value = "用户管理接口说明", description = "用户管理接口说明")
@RestController
@RequestMapping(value = "/user/userinfo")
public class SysUserController extends BaseController {

    @Autowired
    private SysUserService sysUserService;

    @Autowired
    private SysRoleService sysRoleService;

    @Autowired
    private ShiroService shiroService;

    @Value("${password.salt}")
    private String salt ;

    @Value("${password.hashIterations}")
    private Integer hashIterations;

    @ApiOperation(value = "根据部门编号查询所有用户", httpMethod = "GET", response = SysUser.class)
    @GetMapping("/list")
    public Object getDeparts(@ApiParam(value = "部门编号。（必填）") @RequestParam String storeCode,
                             @ApiParam(value = "账户或用户名") @RequestParam(required = false, defaultValue = "") String searchKey,
                             @ApiParam(value = "当前页数") @RequestParam(required = false, defaultValue = "0") Integer pageNum,
                             @ApiParam(value = "分页数量") @RequestParam(required = false, defaultValue = "30") Integer pageSize) {
        return setSuccessMyMap(sysUserService.getDeparts(storeCode, searchKey, pageNum, pageSize));
    }

    @ApiOperation(value = "用户查询或状态", httpMethod = "GET", response = SysUser.class)
    @GetMapping("/status/{account}")
    public Object getAccount(@PathVariable String account){
        return setSuccessMyMap(sysUserService.findByAccount(account));
    }

    /**
     * @return
     * @throws Exception
     */
    @ApiOperation(value = "新增用户并添加角色信息", httpMethod = "POST", response = SysUser.class)
    @PostMapping
    public Object post(@RequestParam(required = false) Set<Integer> roleIds,
                       @RequestBody SysUser sysUser){
        if ( !sysUserService.existByAccount(sysUser.getAccount()) && sysUser.getPassword() != null ){
            sysUser.setPassword(new Md5Hash(sysUser.getPassword(), salt,hashIterations).toString());
            if ( !CollectionUtils.isEmpty(roleIds) ) {
                Set<SysRole> sysRoles = sysRoleService.findAllSysRoleById(roleIds);
                sysUser.setSysRoles(sysRoles);
            }
            return setSuccessMyMap(sysUserService.add(sysUser));
        }else {
            throw new MyException(MyError.USER_EXISTS);
        }

    }

    @ApiOperation(value = "修改用户角色信息", httpMethod = "PUT", response = SysUser.class)
    @PutMapping
    public Object put(@RequestParam(required = false) Set<Integer> roleIds,
                      @RequestBody SysUser sysUser){
        if (sysUserService.existByAccount(sysUser.getAccount())){
            if (!CollectionUtils.isEmpty(roleIds)){
                Set<SysRole> sysRoles = sysRoleService.findAllSysRoleById(roleIds);
                sysUser.setSysRoles(sysRoles);
            }
            return setSuccessMyMap(sysUserService.update(sysUser));
        } else {
            throw new MyException(MyError.USER_NOT_EXISTS);
        }

    }

    @ApiOperation(value = "编辑用户数据权限", httpMethod = "PUT", response = SysUser.class)
    @PutMapping("/datapermition")
    public Object datapermition(@RequestParam Integer id,
                                @RequestParam Set<String> dataPermitions) {
        SysUser sysUser = sysUserService.queryById(id);
        sysUser.setDataPermition(dataPermitions);
        return setSuccessMyMap(sysUserService.update(sysUser));
    }

    @ApiOperation(value = "更改用户启禁用状态", httpMethod = "PUT", response = SysUser.class)
    @PutMapping("/status")
    public Object putState(@RequestParam Integer id, @RequestParam boolean isEnabled) {
        SysUser sysDepart = sysUserService.queryById(id);
        sysDepart.setIsEnabled(isEnabled);
        return setSuccessMyMap(sysUserService.update(sysDepart));
    }

    @ApiOperation(value = "更改密码", httpMethod = "PUT", response = SysUser.class)
    @PutMapping("/password")
    public Object changePassword(@RequestParam String oldPassword,
                                 @RequestParam String newPassword) {
        Assert.notNull(oldPassword, "旧密码不能为空！");
        Assert.notNull(newPassword, "新密码不能为空！");
        SysUser sysUser = shiroService.getSysUser();
        if (new Md5Hash(oldPassword, salt,hashIterations).toString().equals(sysUser.getPassword())){
            sysUser.setPassword(new Md5Hash(newPassword, salt,hashIterations).toString());
            return setSuccessMyMap("密码修改成功！");
        }else {
            throw new MyException(MyError.PASSWORD_WRONG);
        }

    }

    @ApiOperation(value = "删除用户", httpMethod = "DELETE", response = void.class)
    @DeleteMapping("/{id}")
    public Object delete(@PathVariable Integer id) {
        sysUserService.delete(id);
        return setSuccessMyMap(null);
    }

}